/**
 * 
 */
package leetCode;

/**
 * @author zhong
 *
 */
public class ValidTicTacToeState {
	public boolean validTicTacToe(String[] board) {
		int countX = 0, countO = 0;
		for (String string : board) {
			for (int i = 0; i < string.length(); i++) {
				switch (string.charAt(i)) {
				case 'X':
					countX++;
					break;
				case 'O':
					countO++;
					break;
				default:
					break;
				}
			}
		}
		int diff = countX - countO;
		if (!(diff == 0 || diff == 1)) {
			return false;
		}
		boolean[] row = new boolean[3];
		boolean[] col = new boolean[3];
		boolean[] dig = new boolean[2];
		boolean bolX = false, bolO = false;
		for (int i = 0; i < 3; i++) {// 同一行
			String string = board[i];
			row[i] = string.charAt(2) != ' ' && string.charAt(0) == string.charAt(1)
					&& string.charAt(1) == string.charAt(2);
			if (row[i]) {
				if (string.charAt(0) == 'X') {
					bolX = true;
				} else if (string.charAt(0) == 'O') {
					bolO = true;
				}
			}
			col[i] = board[2].charAt(i) != ' ' && board[1].charAt(i) == board[0].charAt(i)
					&& board[1].charAt(i) == board[2].charAt(i);
			if (col[i]) {
				if (board[0].charAt(i) == 'X') {
					bolX = true;
				} else if (board[0].charAt(i) == 'O') {
					bolO = true;
				}
			}
		}
		dig[0] = board[0].charAt(0) == board[1].charAt(1) && board[2].charAt(2) == board[0].charAt(0);
		if (dig[0]) {
			if (board[0].charAt(0) == 'X') {
				bolX = true;
			} else if (board[0].charAt(0) == 'O') {
				bolO = true;
			}
		}
		dig[1] = board[0].charAt(2) == board[1].charAt(1) && board[1].charAt(1) == board[2].charAt(0);
		if (dig[1]) {
			if (board[0].charAt(2) == 'X') {
				bolX = true;
			} else if (board[0].charAt(2) == 'O') {
				bolO = true;
			}
		}
		System.out.println(bolX);
		System.out.println(bolO);

		if (bolO) {
			if (bolX)
				return false;
			if (diff != 0)
				return false;
		}
		if (bolX) {
			if (diff != 1) {
				return false;
			}
		}
		// 只要不能多行/列一样就行
		int countSame = 0;
		for (boolean b : row) {
			if (b)
				countSame++;
		}
		if (countSame > 1)
			return false;
		countSame = 0;
		for (boolean b : col) {
			if (b)
				countSame++;
		}
		if (countSame > 1)
			return false;
		return true;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String[] board = { "X  ", "   ", "   " };
		System.out.println(new ValidTicTacToeState().validTicTacToe(board));
	}

}
